package com.lwy.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lwy.entity.MyBookUser;
import com.lwy.jwt.JWTUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


@Component
public class MySuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        MyBookUser principal = (MyBookUser) authentication.getPrincipal();
        Map<String,Object> map = new HashMap<>();
        map.put("code","200");
        map.put("msg","认证成功");
        String token = JWTUtils.getToken(authentication);
        map.put("token",token);
        map.put("principal",principal);


        ObjectMapper objectMapper = new ObjectMapper();
        String string = objectMapper.writeValueAsString(map);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(string);
        writer.flush();
        writer.close();
    }
}
